<script>
	import {
		getChainInfo,
		getApp_config
	} from './http/api.js'
	import getAppVersion from '@/js_sdk/common/updataApp.js'
	export default {
		onLaunch: async function() {
			// #ifdef APP-PLUS
			await this.checkNetworkPermission();
			// #endif
		},
		onShow: async function() {
			// Only try to update app if we have network
			const hasNetwork = await this.checkNetworkStatus();
			if (hasNetwork) {
				this.upApp();
			}
		},
		onHide: function() {},
		methods: {
			// Helper method to check network status
			checkNetworkStatus() {
				return new Promise((resolve) => {
					uni.getNetworkType({
						success: (res) => {
							const networkType = res.networkType.toLowerCase();
							const validNetworks = ['wifi', '2g', '3g', '4g', '5g', 'ethernet'];
							if (networkType === 'none') {
								resolve(false);
							} else if (validNetworks.includes(networkType)) {
								resolve(true);
							} else {
								console.warn('未知网络类型:', networkType);
								resolve(false); // Treat unknown as no network
							}
						},
						fail: (err) => {
							console.log('获取网络状态失败:', err);
							resolve(false);
						}
					});
				});
			},

			async checkNetworkPermission() {
				const hasNetwork = await this.checkNetworkStatus();
				if (!hasNetwork) {
					this.showNetworkPermissionModal();
					return false;
				}
				// Only proceed with chain info if we have network
				await this.getChain();
				return true;
			},

			showNetworkPermissionModal() {
				uni.showModal({
					title: '网络权限提示',
					content: '请允许应用使用网络，否则部分功能无法正常使用。请前往「设置」>「蜂窝网络」> 找到本应用，并允许「无线局域网 & 蜂窝网络」',
					confirmText: '明白了',
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							// #ifdef APP-PLUS
							plus.runtime.openURL('app-settings:');
							// #endif
						}
					}
				});
			},

			upApp() {
				getApp_config().then(res => {
					console.log(res)
					if(res.code==200){
						getAppVersion(res.data.version,res.data.url)
						if(res.data.status=="0"){
							this.$store.commit('setAppstatus', 0);
						}
					}
				})
			},

			async getChain() {
				try {
					const res = await getChainInfo();
					if (res.code == 200) {
						let list = res.data?.map(chain => ({
							chainId: chain.chainId,
							defultRPC: chain.defultRPC
						}));
						let allchains = uni.getStorageSync('allchains') || {};
						let rpclist = uni.getStorageSync('rpclist') || [];
						if (!allchains || JSON.stringify(allchains) != JSON.stringify(res.data)) {
							this.$store.commit('setAllchains', res.data);
						}
						if (!rpclist || list?.length != rpclist?.length) {
							let newChains = list.filter(chain => !rpclist.some(rpc => rpc.chainId === chain.chainId));
							if (newChains.length > 0) {
								rpclist = [...rpclist, ...newChains];
							}
							uni.setStorageSync('rpclist', rpclist);
						}
					}
					this.$updateWalletInfo()
				} catch (error) {
					console.error('Failed to get chain info:', error);
				}
			}
		}
	}
</script>

<style lang="scss">
	.uni-dialog-title {
		.uni-popup__info {
			color: #3D3D3D;

			.uni-dialog-title-text {
				font-size: 36upx;
				font-weight: 400;
			}
		}
	}
</style>